import { Directive, HostListener, ElementRef, Renderer, Input, OnInit, AfterViewInit, AfterViewChecked, AfterContentChecked, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';

@Directive({
    selector: '[modal-body]'
})
export class ModalBodyDirective implements AfterViewChecked 
{ 
    @Output('maxheight') maxheightChange: EventEmitter<number> = new EventEmitter();

    constructor(public element: ElementRef, public renderer: Renderer) {
        //console.log('自适应');
    }

    ngAfterViewChecked(): void {
        this.SetHeight();
    }


    SetHeight(event?: any){
        let eventTarget = event == undefined ? window : event.target;
        let wh = eventTarget.innerHeight;

        let modalbody:HTMLElement = this.element.nativeElement;
        let contentheight = modalbody.firstElementChild.getBoundingClientRect().height + 30;
        // console.log( modalbody.firstElementChild.getBoundingClientRect().height);
        if (modalbody.previousElementSibling)
            wh = wh - modalbody.previousElementSibling.clientHeight-20;
        if (modalbody.nextElementSibling)
            wh = wh - modalbody.nextElementSibling.clientHeight-20;
        if(wh>contentheight){
            this.renderer.setElementStyle(this.element.nativeElement, 'height', 'auto');
            this.renderer.setElementStyle(this.element.nativeElement, 'overflow', 'visible');
        }
        else{
            this.maxheightChange.emit(wh-30);
            this.renderer.setElementStyle(this.element.nativeElement, 'height',wh + 'px');
            this.renderer.setElementStyle(this.element.nativeElement, 'minHeight',wh + 'px');
            this.renderer.setElementStyle(this.element.nativeElement, 'overflow', 'auto');
        }
    }
}